package com.im.imservice.handler;

import com.im.imservice.config.CurrentChannelInfo;
import com.im.imservice.config.MessageAsyncSendCallback;
import com.im.imservice.config.SpringBeanUtil;
import com.im.imservice.enity.ImServerInfo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

/**
 * 连接断开时，将消息发送到mq
 * 修改用户在线状态
 */
@Slf4j
public class RemovedHandler extends SimpleChannelInboundHandler<CloseWebSocketFrame> {

    private static RocketMQTemplate rocketMQTemplate;

    private static MessageAsyncSendCallback asyncSendCallback;

    private final static String TAG = "logOut";

    private final static String TOP = "message_top:"+TAG;



    static {
        rocketMQTemplate =  SpringBeanUtil.getBean(RocketMQTemplate.class);
        asyncSendCallback =  SpringBeanUtil.getBean(MessageAsyncSendCallback.class);
    }


    /**
     * 通过消息队列 执行用户登录操作 并且删除map中的用户信息
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("用户退出执行");
        AttributeKey<String> key = AttributeKey.valueOf(ctx.channel().id().asLongText());
        String id = ctx.channel().attr(key).get();
        ImServerInfo imServerInfo = ImServerInfo.builder().tag(TAG).body(id).build();
        Message<ImServerInfo> msg = MessageBuilder.withPayload(imServerInfo).build();
//        rocketMQTemplate.asyncSend(TOP, msg,asyncSendCallback);
        CurrentChannelInfo.deleteChannel(ctx.channel());
        log.info("用户退出执行完毕");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CloseWebSocketFrame msg) throws Exception {
        if (msg instanceof CloseWebSocketFrame) {
            ctx.channel().close();
            return;
        }
        log.info("");
    }
}
